// const HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
const pack = require("./package.json");
const dayjs = require("dayjs");
const ZipDist = require('./zip')
const { exec } = require("child_process");
const { VUE_APP_WEBSOCKET, VUE_APP_APIHOST, VUE_APP_WEBSITE, NODE_ENV, VUE_APP_ENV, VUE_APP_OSSHOST } = process.env;
const isProd = NODE_ENV === "production";
console.log({ VUE_APP_WEBSOCKET, VUE_APP_APIHOST, VUE_APP_WEBSITE, NODE_ENV, VUE_APP_ENV });
// 代理列表
const PROXY_LIST = {
	"/dev": {
		target: "http://127.0.0.1:8001",
		changeOrigin: true,
		pathRewrite: {
			"^/dev": ""
		}
	},

	"/pro": {
		target: "https://show.cool-admin.com",
		changeOrigin: true,
		pathRewrite: {
			"^/pro": "/api"
		}
	}
};

const CDN_LIST = {
	css: [
		VUE_APP_OSSHOST + "/static/nprogress.css",
		// "https://cdn.jsdelivr.net/npm/element-ui@2.13.2/lib/theme-chalk/index.css",
		VUE_APP_OSSHOST + "/static/quill.snow.css"
	],
	js: [
		// "https://cdn.jsdelivr.net/npm/qs@6.10.1/dist/qs.min.js",
		VUE_APP_OSSHOST + "/static/qs.js",
		VUE_APP_OSSHOST + "/static/nprogress.js",
		VUE_APP_OSSHOST + "/static/vue.runtime.min.js",
		// "https://cdn.jsdelivr.net/npm/vue-router@3.2.0/dist/vue-router.min.js",
		VUE_APP_OSSHOST + "/static/vuex.min.js",
		VUE_APP_OSSHOST + "/static/axios.min.js",
		VUE_APP_OSSHOST + "/static/lodash.min.js",
		VUE_APP_OSSHOST + "/static/dayjs.min.js",
		VUE_APP_OSSHOST + "/static/vue-rws.umd.js",
		VUE_APP_OSSHOST + "/static/FileSaver.min.js",
		VUE_APP_OSSHOST + "/static/store.legacy.min.js",
		// "https://cdn.jsdelivr.net/npm/xlsx@0.16.9/dist/xlsx.min.js",
		VUE_APP_OSSHOST + "/static/clipboard.min.js",
		VUE_APP_OSSHOST + "/static/quill.min.js"
		// "https://cdn.jsdelivr.net/npm/wangeditor@4.6.14/dist/wangEditor.min.js"
	]
};
const date = dayjs().format("YYYYMMDDHHmmss");
let outputDir = `dist/${VUE_APP_ENV || "dev"}/${date}`;
module.exports = {
	outputDir,
	publicPath: "/",
	lintOnSave: true,
	productionSourceMap: false,
	parallel: require("os").cpus().length > 1,
	css: {
		extract: isProd,
		sourceMap: false,
		loaderOptions: {
			sass: {
				prependData: `@import "@/assets/css/common.scss";`
			}
		}
	},
	pwa: {
		name: "宸羽",
		themeColor: "#156DFF",
		backgroundColor: "#2f3447",
		msTileColor: "#2f3447"
	},
	devServer: {
		port: 9300,
		open: false,
		compress: false,
		overlay: {
			warnings: false,
			errors: true
		},
		disableHostCheck: true,
		proxy: {
			"/api": {
				target: "http://zmweb.vaiwan.com",
				changeOrigin: true,
				pathRewrite: {
					"^/api": "/api"
				}
			}
		}
	},
	chainWebpack: config => {
		// 设置环境变量
		config.plugin("define").tap(args => {
			args[0]["process.env"].PROXY_LIST = JSON.stringify(PROXY_LIST);
			return args;
		});

		// 生产环境注入cdn
		config.plugin("html").tap(args => {
			args[0].link = VUE_APP_WEBSITE;
			if (isProd) {
				args[0].cdn = CDN_LIST;
			}
			return args;
		});
		// 设置 svg
		config.module.rule("svg").uses.clear();

		config.module
			.rule("svg-sprite-loader")
			.test(/.svg$/)
			.exclude.add(/node_modules/)
			.end()
			.use("svg-sprite-loader")
			.loader("svg-sprite-loader")
			.options({
				symbolId: "[name]"
			});

		// it can improve the speed of the first screen, it is recommended to turn on preload
		// it can improve the speed of the first screen, it is recommended to turn on preload
		config.plugin("preload").tap(() => [
			{
				rel: "preload",
				// to ignore runtime.js
				// https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
				fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
				include: "initial"
			}
		]);
		// 生产环境配置
		if (isProd) {
			// 给js和css配置版本号
			config.output.filename(`js/[name].js?v=${pack.version}&t=${date}`).end();
			config.output.chunkFilename(`js/[name].js?v=${pack.version}&t=${date}`).end();
			config.plugin("extract-css").tap(args => [
				{
					filename: `css/[name].css?v=${pack.version}&t=${date}`,
					chunkFilename: `css/[name].css?v=${pack.version}&t=${date}`
				}
			]);
			// 移除 prefetch 插件
			config.plugins.delete("prefetch");
			// 移除 preload 插件
			config.plugins.delete("preload");

			// 去掉元素之间空格
			config.module
				.rule("vue")
				.use("vue-loader")
				.loader("vue-loader")
				.tap(options => {
					options.compilerOptions.preserveWhitespace = true;
					return options;
				})
				.end();

			config.optimization.minimizer("terser").tap(args => {
				// 去掉注释
				args[0].terserOptions.output = { comments: false };
				return args;
			});
			// ============压缩图片 start============
			config.module
				.rule("images")
				.use("image-webpack-loader")
				.loader("image-webpack-loader")
				.options({
					limit: 10000,
					bypassOnDebug: true
				})
				.end();
			// ============压缩图片 end============
			config.when(isProd, config => {
				config
					.plugin("ScriptExtHtmlWebpackPlugin")
					.after("html")
					.use("script-ext-html-webpack-plugin", [
						// `runtime` must same as runtimeChunk name. default is `runtime`
						{ inline: /runtime\..*\.js$/ }
					])
					.end();
				config.optimization.splitChunks({
					chunks: "all",
					// minSize: 30 * 1024, //字节 引入的文件大于30kb才进行分割
					maxSize: 5 * 1024 * 1024, //尝试将大于2mb的文件拆分成n个2mb的文件
					maxAsyncRequests: 5, //同时加载的模块数量最多是5个，只分割出同时引入的前5个文件
					maxInitialRequests: 3, //首页加载的时候引入的文件最多3个
					cacheGroups: {
						libs: {
							name: "chunk-libs",
							test: /[\\/]node_modules[\\/]/,
							priority: 10,
							chunks: "initial" // only package third parties that are initially dependent
						},
						elementUI: {
							name: "chunk-elementUI", // split elementUI into a single package
							priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
							test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
						}
					}
				});
				// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
				config.optimization.runtimeChunk("single");
			});
		}
	},

	configureWebpack: config => {
		if (isProd) {
			// 用cdn方式引入
			config.externals = {
				axios: "axios",
				nprogress: "NProgress",
				lodash: "_",
				dayjs: "dayjs",
				"vue-rws": "VueRws",
				FileSaver: "FileSaver",
				store: "store",
				Qs: "qs",
				// XLSX: "XLSX",
				ClipboardJS: "Clipboard",
				Quill: "Quill",
				// wangeditor: "E",
				vue: "Vue",
				vuex: "Vuex"
				// "vue-router": "VueRouter"
			};
			// 为生产环境修改配置...
			if (VUE_APP_ENV != 'dev') {
				config.plugins.push(new ZipDist())
			}
			// config.plugins.push({
			// 	apply: compiler => {
			// 		compiler.hooks.done.tap("execZip", compilation => {
			// 			// do something when webpack compilation done
			// 			exec(
			// 				`node zip.js dir=${outputDir} time=${date} env=${VUE_APP_ENV}`,
			// 				(error, stdout, stderr) => {
			// 					if (error) {
			// 						console.error(`执行的错误: ${error}`);
			// 						return;
			// 					}
			// 					console.log(`stdout: ${stdout}`);
			// 				}
			// 			);
			// 		});
			// 	}
			// });
		}
		// 构建缓存 经常出问题暂时注释
		// config.plugins.push(new HardSourceWebpackPlugin());
		// config.plugins.push(
		// 	new HardSourceWebpackPlugin({
		// 		// cacheDirectory是在高速缓存写入。默认情况下，将缓存存储在node_modules下的目录中，因此如
		// 		// 果清除了node_modules，则缓存也是如此
		// 		cacheDirectory: "node_modules/.cache/hard-source/[confighash]",
		// 		// Either an absolute path or relative to webpack's options.context.
		// 		// Sets webpack's recordsPath if not already set.
		// 		recordsPath: "node_modules/.cache/hard-source/[confighash]/records.json",
		// 		// configHash在启动webpack实例时转换webpack配置，并用于cacheDirectory为不同的webpack配
		// 		// 置构建不同的缓存
		// 		configHash: webpackConfig => {
		// 			// node-object-hash on npm can be used to build this.
		// 			return require("node-object-hash")({ sort: false }).hash(webpackConfig);
		// 		},
		// 		// 当加载器，插件，其他构建时脚本或其他动态依赖项发生更改时，hard-source需要替换缓存以确保输
		// 		// 出正确。environmentHash被用来确定这一点。如果散列与先前的构建不同，则将使用新的缓存
		// 		environmentHash: {
		// 			root: process.cwd(),
		// 			directories: [],
		// 			files: ["package-lock.json", "yarn.lock"]
		// 		}
		// 	})
		// );
	}
};
